using Dapper;
using MediatR;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Write.Api.Application.Command.ERP.SalesManagement.H;
using System.Data;
using System;
using static RBAC.ErrorCode.APIEnums;

namespace RBAC.Write.Api.Application.Handler.ERP.SalesManagement
{
    /// <summary>
    /// 审核/反审核/退回 发货通知单 处理器（仅更新 Delivery_notice.Status）
    /// 0 = 开立，1 = 审批，2 = 退回
    /// </summary>
    public class ApproveOrReturnDeliveryNoticeHandler : IRequestHandler<ApproveOrReturnDeliveryNoticeCommand, APIResult<bool>>
    {
        private readonly IDbConnectionFactory _dbConnectionFactory;

        public ApproveOrReturnDeliveryNoticeHandler(IDbConnectionFactory dbConnectionFactory)
        {
            _dbConnectionFactory = dbConnectionFactory;
        }

        public async Task<APIResult<bool>> Handle(ApproveOrReturnDeliveryNoticeCommand request, CancellationToken cancellationToken)
        {
            if (request.Action < 0 || request.Action > 2)
            {
                return new APIResult<bool> { Code = Error, Msg = "无效的操作：仅支持 0=开立，1=审批，2=退回", Data = false };
            }

            IDbConnection? conn = null;
            IDbTransaction? tran = null;

            try
            {
                conn = _dbConnectionFactory.CreateConnection();
                tran = conn.BeginTransaction();

                // 1) 查询当前状态，校验是否存在
                var currentStatus = await conn.QueryFirstOrDefaultAsync<int?>(
                    "SELECT Status FROM Delivery_notice WHERE Id = @Id",
                    new { Id = request.Id }, tran);

                if (currentStatus is null)
                {
                    tran.Rollback();
                    return new APIResult<bool> { Code = Error, Msg = "发货通知单不存在", Data = false };
                }

                // 2) 如状态相同，直接返回提示
                if (currentStatus.Value == request.Action)
                {
                    tran.Rollback();
                    return new APIResult<bool> { Code = Error, Msg = "当前状态已是目标状态", Data = false };
                }

                // 3) 更新状态 + 审核信息（审核：写入审核人和时间；反审核/退回：清空审核人和时间）
                var rows = await conn.ExecuteAsync(
                    @"UPDATE Delivery_notice
                       SET Status = @Status,
                           Audit_user_id = CASE WHEN @Status = 1 THEN @AuditUserId ELSE NULL END,
                           Audit_time    = CASE WHEN @Status = 1 THEN @Now        ELSE NULL END
                     WHERE Id = @Id",
                    new
                    {
                        Status = request.Action,
                        Id = request.Id,
                        AuditUserId = request.AuditUserId,
                        Now = DateTime.Now
                    }, tran);

                if (rows <= 0)
                {
                    tran.Rollback();
                    return new APIResult<bool> { Code = Error, Msg = "更新失败", Data = false };
                }

                tran.Commit();
                return new APIResult<bool>
                {
                    Code = Success,
                    Msg = request.Action switch
                    {
                        1 => "审核成功",
                        2 => "退回成功",
                        _ => "反审核成功"
                    },
                    Data = true
                };
            }
            catch (Exception ex)
            {
                try { tran?.Rollback(); } catch { }
                return new APIResult<bool> { Code = Error, Msg = $"状态更新异常: {ex.Message}", Data = false };
            }
            finally
            {
                try { tran?.Dispose(); } catch { }
                try { conn?.Dispose(); } catch { }
            }
        }
    }
}
